//
//  RootViewController.m
//  reacticons
//
//  Created by Nong Nghia on 4/14/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "RootViewController.h"
#import "TestFlight.h"
#import "ImageListViewController.h"
#import "HeaderViewController.h"

#import "CMCImageVIew.h"
#import "AppDelegate.h"
#import "EGOImageLoader.h"
#import "SearchTagViewController.h"
#import "Utilities.h"


#import "DatabaseConnection.h"
#import "Photo.h"
#import "LoadingView.h"
#import "Category.h"

#import "CMCTumblrRequestHelper.h"
#import "Globals.h"

#import "CMCOperationQueue.h"
#import "TumblrRequestHelper.h"

#define CLEAR_CACHE_ALERT 1
#define kTumblrRequestAllListPhotoSuccess @"kTumblrRequestAllListPhotoSuccess"
#define kTumblrRequestAllListPhotoFailure @"kTumblrRequestAllListPhotoFailure"

#define kTumblrRequestBlockPhotoSuccess @"kTumblrRequestBlockPhotoSuccess"
#define kTumblrRequestBlockPhotoFailure @"kTumblrRequestBlockPhotoFailure"

@interface RootViewController (internal)


@end

@implementation RootViewController

@synthesize itemPerRow = _itemPerRow;
@synthesize parentID = _parentID;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _searchTagList = [[SearchTagViewController alloc] initWithNibName:@"SearchTagViewController" bundle:nil];

    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[self navigationController] setNavigationBarHidden:NO animated:NO];
    [self.navigationItem setTitle:@"Reacticons"];
    NSString *initInfo=[[NSUserDefaults standardUserDefaults] objectForKey:@"LIST_UPDATING"];
    
    [headerController checkUpdate];

    if ([initInfo isEqualToString:@"UPDATE_SUCCESS"]) {
        [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"LIST_UPDATING"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        folderList = [[DatabaseConnection getDefaultCategories] retain];
        [itemGridView reloadData];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    static UIImageView *titleImageView;
    if (!titleImageView) {
        titleImageView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"reacticons_title.png"]] retain];
    }
    [self.navigationItem setTitleView:titleImageView];

    NSString *initInfo=[[NSUserDefaults standardUserDefaults] objectForKey:@"LIST_UPDATING"];

    [headerController checkUpdate];
    
    if ([initInfo isEqualToString:@"UPDATE_SUCCESS"]) {
        [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"LIST_UPDATING"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        folderList = [[DatabaseConnection getDefaultCategories] retain];
        [itemGridView reloadData];
        
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [TestFlight passCheckpoint:@"RootViewController - viewDidLoad"];

    [self.view setBackgroundColor:[UIColor blackColor]];
        
    UIBarButtonItem * searchBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(settingsButtonClick:)];
    [searchBarButton setTag:0];
    
    [self.navigationItem setRightBarButtonItem:searchBarButton];
//    [searchButton release];
    [searchBarButton release];

    folderList = [[NSMutableArray alloc] init];
    
    NSString *initInfo=[[NSUserDefaults standardUserDefaults] objectForKey:@"INIT_DATA"];
    tumRequest=[[TumblrRequestHelper alloc] init];
    if (![initInfo isEqualToString:@"SUCCESS"]) {
        [TestFlight passCheckpoint:@"RootViewController - viewDidLoad - INIT_FIRST_TIME"];
        [[LoadingView sharedInstance] showInitLoadingView];
        [tumRequest getListTumblr];


        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDatabaseFinish:) name:kTumblrRequestAllListPhotoSuccess object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDatabaseFinish:) name:kTumblrRequestBlockPhotoSuccess object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDatabaseFailed:) name:kTumblrRequestAllListPhotoFailure object:nil];

    }
    else {
        [TestFlight passCheckpoint:@"RootViewController - viewDidLoad - INIT_FROM_SECOND_TIME"];
        folderList=[[DatabaseConnection getDefaultCategories] retain];

        [itemGridView removeFromSuperview];
        [itemGridView release];
        itemGridView=nil;
        itemGridView = [[UIGridView alloc] initWithFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-44-43)];
        [itemGridView setNumberOfExtraRows:100];
        headerController = [[HeaderViewController alloc] init];
        headerController.delegate=self;
        [itemGridView setHeaderView:headerController.view];
        [self.view addSubview:itemGridView];
        [itemGridView setBackgroundColor:[UIColor clearColor]];
        [itemGridView setDelegate:self];
        [itemGridView setDataSource:self];
                                                        
    }
    
//    UIButton * settingButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [settingButton setFrame:CGRectMake(0, 0, 46, 26)];
//    [settingButton setImage:[UIImage imageNamed:@"settings_button.png"] forState:UIControlStateNormal];
//    [settingButton addTarget:self action:@selector(btnWasClicked:) forControlEvents:UIControlEventTouchUpInside];
//    [settingButton setTag:12];
    settingBtn =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"settings_button.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(btnWasClicked:)];
    [settingBtn setTag:12];
    [self.navigationItem setLeftBarButtonItem:settingBtn];
    
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Buttons On Click

- (void)settingsButtonClick:(id)sender
{

    [_searchTagList setDelegate:self];
    [_searchTagList setTableData:[[NSUserDefaults standardUserDefaults] objectForKey:@"TAGS_ARRAY"]];
    DBLOG(@"%@",_searchTagList.tableData);
    [self presentModalViewController:_searchTagList animated:NO];

}

#pragma mark - Grid View Data Source

- (CGFloat)gridView:(UIGridView *)gridView heightForRowAtIndex:(NSInteger)rowIndex
{
    return 100;
}

- (NSInteger)numberOfCellsInGridView:(UIGridView *)gridView
{   DBLOG(@"RootViewController - numberOfCellsInGridView - %d",[folderList count]);
    return [folderList count];
}

- (NSInteger)gridView:(UIGridView *)gridView numberOfCellsPerRowInRow:(NSInteger)rowIndex
{
    return 3;
}

- (GridViewCell*)gridView:(UIGridView *)gridView cellAtIndex:(NSInteger)cellIndex
{

    UIGridViewCell_DownloadImage * cell = [[[UIGridViewCell_DownloadImage alloc] initWithFrame:CGRectZero] autorelease];
    Category * category = [folderList objectAtIndex:cellIndex];

    [cell.imageView setContentMode:UIViewContentModeScaleAspectFill];
    
    cell.egoImageView=[[[CMCImageView alloc] init] autorelease];
    
    if (category != nil && ![category.categoryThumbnailPath isEqualToString:@""])
        [cell setImageURLString:category.categoryThumbnailPath];
    
    [cell.textLabel setText:[NSString stringWithFormat:@"%@", category.categoryName]];
    [cell setAccessoryType:UIGridViewCellAccessoryNone];
    return cell;
}

#pragma mark - Grid View Delegate


- (void)gridView:(UIGridView *)gridView didSelectedCellAtIndex:(NSInteger)cellIndex
{
    Category * category = [folderList objectAtIndex:cellIndex];
    ImageListViewController * rootView = [[ImageListViewController alloc] init];
    [rootView setParentID:[NSString stringWithFormat:@";%@;",category.categoryName]];
    [rootView setTitle:category.categoryName];
    [self.navigationItem setTitle:@"Categories"];
    [self.navigationController pushViewController:rootView animated:YES];
}

- (void)gridView:(UIGridView*)gridView didLongPressCellAtIndex:(NSInteger)cellIndex
{
    
}

#pragma mark - Update View After Update Database

-(void)updateDatabaseFinish:(NSNotification*)notification{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kTumblrRequestAllListPhotoFailure object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kTumblrRequestAllListPhotoSuccess object:nil];
    

    [[LoadingView sharedInstance] stopLoadingView];

    DBLOG(@"RootViewController - updateDatabaseFinish - ");
    self.navigationItem.leftBarButtonItem=settingBtn;
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(canGetDefaultCategoryList:) name:@"kCanGetDefaultCategoryList" object:nil];
    folderList=[[DatabaseConnection getDefaultCategories] retain];
        [[NSUserDefaults standardUserDefaults] setValue:@"SUCCESS" forKey:@"INIT_DATA"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if (itemGridView) {
            [itemGridView removeFromSuperview];
//            [itemGridView release];
//            itemGridView=nil;
        }
        itemGridView = [[UIGridView alloc] initWithFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-44-43)];
        [itemGridView setNumberOfExtraRows:100];
        
        if (headerController) {
            [headerController release];
            headerController = nil;
        }
        
        headerController = [[HeaderViewController alloc] init];
        headerController.delegate=self;
        [itemGridView setHeaderView:headerController.view];
        [self.view addSubview:itemGridView];
        [itemGridView setBackgroundColor:[UIColor clearColor]];
        [itemGridView setDelegate:self];
        [itemGridView setDataSource:self];
}

-(void)updateDatabaseFailed:(NSNotification*)notification{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kTumblrRequestAllListPhotoFailure object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kTumblrRequestAllListPhotoSuccess object:nil];
    DBLOG(@"RootViewController - updateDatabaseFailed - ");

    [[LoadingView sharedInstance] stopLoadingView];
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Error Connection" message:@"Download List From Tumblr failed.\nPlease check your connection!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];
    UIButton * refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [refreshButton setFrame:CGRectMake(0, 0, 46, 26)];
    [refreshButton setBackgroundImage:[UIImage imageNamed:@"right_button.png"] forState:UIControlStateNormal];
    [refreshButton setImage:[UIImage imageNamed:@"settings_button.png"] forState:UIControlStateNormal];
    [refreshButton addTarget:self action:@selector(btnWasClicked:) forControlEvents:UIControlEventTouchUpInside];
    [refreshButton setTag:11];
    UIBarButtonItem *refreshBtn=[[UIBarButtonItem alloc] initWithCustomView:refreshButton];
//    [refreshBtn setTag:11];
    [self.navigationItem setLeftBarButtonItem:refreshBtn];
    [refreshBtn release];
    folderList=[[DatabaseConnection getDefaultCategories] retain];

    itemGridView = [[UIGridView alloc] initWithFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-44-43)];
    [itemGridView setNumberOfExtraRows:100];
    headerController = [[HeaderViewController alloc] initWithNibName:@"HeaderViewController" bundle:nil];
    headerController.delegate=self;
    [itemGridView setHeaderView:headerController.view];
    [self.view addSubview:itemGridView];
    [itemGridView setBackgroundColor:[UIColor clearColor]];
    [itemGridView setDelegate:self];
    [itemGridView setDataSource:self];
}


-(IBAction)btnWasClicked:(id)sender{
    DBLOG(@"%d",[sender tag]);
    if ([sender tag]==11) {
        UIButton * settingButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [settingButton setFrame:CGRectMake(0, 0, 46, 26)];
        [settingButton setBackgroundImage:[UIImage imageNamed:@"right_button.png"] forState:UIControlStateNormal];
        [settingButton setImage:[UIImage imageNamed:@"settings_button.png"] forState:UIControlStateNormal];
        [settingButton addTarget:self action:@selector(btnWasClicked:) forControlEvents:UIControlEventTouchUpInside];
        [settingButton setTag:12];
        
        settingBtn =[[UIBarButtonItem alloc] initWithCustomView:settingButton];
        [self.navigationItem setLeftBarButtonItem:settingBtn];
        [[LoadingView sharedInstance] showInitLoadingView];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDatabaseFinish:) name:kTumblrRequestAllListPhotoSuccess object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDatabaseFinish:) name:kTumblrRequestBlockPhotoSuccess object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDatabaseFailed:) name:kTumblrRequestAllListPhotoFailure object:nil];
        
        [tumRequest getListTumblr];
        return;
    }
    if ([sender tag]==12) {
        NSString *documentPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UPDATING_DATA"] isEqualToString:@"YES"]) {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Cached Data"
                                                          message:[NSString stringWithFormat:@"Total amount used: %3.1f MB\nList is updating! Cannot clear now!",[Utilities sizeOfDirectory:documentPath]/(1024.0*1024.0)]
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles: nil];
            [alert show];
            [alert release];
            return;
        }
        
        
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Cached Data"
                                                      message:[NSString stringWithFormat:@"Total amount used: %3.1f MB\nClear cached images?",[Utilities sizeOfDirectory:documentPath]/(1024.0*1024.0)]
                                                     delegate:self
                                            cancelButtonTitle:@"CANCEL"
                                            otherButtonTitles:@"OK", nil];
        [alert setTag:CLEAR_CACHE_ALERT];
        [alert show];
        [alert release];
        return;
    }
}

#pragma mark - Search Tag View Delegate

- (void)searchTagViewController:(id)viewController didSelectTag:(id)selectObject
{
    if ([viewController isEqual:_searchTagList]) {
        DBLOG(@"Tag selected: %@", selectObject);
        ImageListViewController * rootView = [[ImageListViewController alloc] init];

        [rootView setParentID:[NSString stringWithFormat:@";%@;",selectObject]];
        [rootView setTitle:selectObject];
        [self.navigationItem setTitle:@"Categories"];
        [self.navigationController pushViewController:rootView animated:YES];
        
    }
}


-(void)clickedHeaderBtn:(id)sender{
    switch ([sender tag]) {
        case 0:
            //  Call the view of all images
            DBLOG(@"Folder of all images");
            ImageListViewController * rootView = [[ImageListViewController alloc] init];
            [rootView setParentID:[@"recentlyAdded" retain]];
            [rootView setTitle:@"Recently Added"];
            [self.navigationController pushViewController:rootView animated:YES];
            [rootView release];
            break;
            
        case 1:
            //  Call the view of recent used images
            DBLOG(@"Folder of recent used images");
            ImageListViewController * rootView2 = [[ImageListViewController alloc] init];
            [rootView2 setParentID:@"recentlyUsed"];
            [rootView2 setTitle:@"Recently Used"];
            [self.navigationController pushViewController:rootView2 animated:YES];
            [rootView2 release];
            break;
            
        default:
            break;
    }
    

}
#pragma mark - UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if ([alertView tag]==CLEAR_CACHE_ALERT) {
        if (buttonIndex==1) {
            NSString *documentFolder=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
            NSArray *fileList=[[NSFileManager defaultManager] subpathsAtPath:documentFolder];
            for (NSString *fileName in fileList) {
                BOOL isDirectory=NO;
                
                fileName=[fileName lastPathComponent];
                
                if ([[NSFileManager defaultManager] fileExistsAtPath:[documentFolder stringByAppendingPathComponent:fileName]
                    isDirectory:&isDirectory]) {
                    
                    if (!isDirectory){
                        if([[[fileName componentsSeparatedByString:@"."] objectAtIndex:1] isEqualToString:@"jpg"]||
                        
                           [[[fileName componentsSeparatedByString:@"."] objectAtIndex:1] isEqualToString:@"png"]) {
                            DBLOG(@"remove:%@",fileName);
                            [[NSFileManager defaultManager] removeItemAtPath:[documentFolder stringByAppendingPathComponent:fileName] error:nil];
                        
                        }
                    }
                    
                }
            }
            
            NSArray *recentlyAddedList=[[NSFileManager defaultManager] subpathsAtPath:[documentFolder stringByAppendingPathComponent:@"TagThumbnail"]];
            for (NSString *fileName in recentlyAddedList) {
                BOOL isDirectory=NO;
                
                fileName=[fileName lastPathComponent];
                
                if ([[NSFileManager defaultManager] fileExistsAtPath:[[documentFolder stringByAppendingPathComponent:@"TagThumbnail"] stringByAppendingPathComponent:fileName]
                                                         isDirectory:&isDirectory]) {
                    
                    if (!isDirectory){
                        if([[[fileName componentsSeparatedByString:@"."] objectAtIndex:1] isEqualToString:@"jpg"]||
                           
                           [[[fileName componentsSeparatedByString:@"."] objectAtIndex:1] isEqualToString:@"png"]) {
//                            DBLOG(@"remove:%@",fileName);
                            [[NSFileManager defaultManager] removeItemAtPath:[[documentFolder stringByAppendingPathComponent:@"TagThumbnail"] stringByAppendingPathComponent:fileName] error:nil];
                            
                        }
                    }
                    
                }
            }
            
            NSMutableArray *arr=[[DatabaseConnection getRecentlyUsedPhotos] retain];
            for (Photo *item in arr) {
                [item setPhotoRecentlyUsed:@"19990102030405"];
                [DatabaseConnection writeListItems:[NSMutableArray arrayWithObject:[item itemObject]] toEntity:@"ManagedTumblrPhoto" withPrimaryKey:@"photoID"];
            }
            [arr release];
            
            [itemGridView removeFromSuperview];
            [headerController removeAllItems];
            [self viewDidLoad];
            [headerController checkUpdate];

        }
    }
}


@end
